package com.chujian.framework.util.mybatis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.chujian.framework.util.Spring;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * mybatis Id 相关工具类
 */
@Slf4j
public class MybatisIdUs {

    private static MybatisPlusProperties mybatisPlusProperties;

    // cache : class -> idType
    private static final Map<Class<?>, IdType> ENTITY_TABLE_ID_TYPE = new ConcurrentHashMap<>();

    public static IdType getIdType(Class<?> entityClass) {
        // use cache
        IdType type = ENTITY_TABLE_ID_TYPE.get(entityClass);
        if (null != type) {
            return type;
        }
        // init
        List<Field> idFields = Arrays.stream(ReflectUtil.getFields(entityClass))
                .filter(e -> null != e.getAnnotation(TableId.class))
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(idFields)) {
            TableId tableId = idFields.get(0).getAnnotation(TableId.class);
            type = tableId.type();

            if (IdType.NONE == type) {
                type = getDefaultIdType();
            }
        } else {
            type = getDefaultIdType();
        }
        ENTITY_TABLE_ID_TYPE.put(entityClass, type);
        return type;
    }

    public static IdType getDefaultIdType() {
        if (null == mybatisPlusProperties) {
            mybatisPlusProperties = Spring.getBean(MybatisPlusProperties.class);
        }
        assert mybatisPlusProperties != null;
        return mybatisPlusProperties.getGlobalConfig().getDbConfig().getIdType();
    }

}
